package com.itheima.getaway.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器
 */
@Component
@Order(-1)
public class AuthrizeFilter implements GlobalFilter{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1获取请求参数token
        String authorization = exchange.getRequest().getQueryParams().getFirst("authorization");
        //2.判断请求头是否传递
        if (authorization!=null  && authorization.equals("admin")){
            //3.放行
            return chain.filter(exchange);
        }
        //4.拦截
        ServerHttpResponse response = exchange.getResponse();
        //响应401,未登录状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
